package com.cos.controller.app.appuser;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cos.controller.base.BaseController;
import com.cos.service.information.pictures.PicturesService;
import com.cos.service.interfaces.role.IntMenuService;
import com.cos.service.system.appuser.AppuserService;
import com.cos.util.AppUtil;
import com.cos.util.Const;
import com.cos.util.DateUtil;
import com.cos.util.FileUpload;
import com.cos.util.NumberUtil;
import com.cos.util.PageData;
import com.cos.util.PathUtil;
import com.cos.util.ResponseUtil;
import com.cos.util.StringUtil;
import com.cos.util.Tools;
import com.cos.util.Watermark;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


/**
  * 会员-接口类 
  *    
  * 相关参数协议：
  * 00	请求失败
  * 01	请求成功
  * 02	用户名或密码错误
  * 03	请求协议参数不完整    
  * 04  用户名或密码错误
  * 05  FKEY验证失败
  * 06  短信验证码不正确
  * 07  用户名存在
  * 08  用户名不存在
 */
@Controller
@RequestMapping(value="/appuser")
public class IntAppuserController extends BaseController {
    
	@Resource(name="appuserService")
	private AppuserService appuserService;
	
	@Resource
	private IntMenuService intMenuService;
	
	@Resource(name="picturesService")
	private PicturesService picturesService;
	/**
	 * 根据用户名获取会员信息
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/getAppuserByUm")
	@ResponseBody
	public Object getAppuserByUsernmae() throws UnsupportedEncodingException{
		logBefore(logger, "根据用户名获取会员信息");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		
		try{
			if(Tools.checkKey("USERNAME", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("getAppuserByUsernmae", pd)){	//检查参数
					pd = appuserService.findByUId(pd);
					
					map.put("pd", pd);
					result = (null == pd) ?  "02" :  "01";
					
				}else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
	/**
	 * 用户登录
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/login")
	@ResponseBody
	public Object login() throws UnsupportedEncodingException{
		logBefore(logger, "登录用户");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getAppuserByUsernmae", pd)){	//检查参数
				String password = new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString() ;
				pd.put("PASSWORD", "password") ;
				pd = appuserService.getUserByNameAndPwd(pd);
					
				map.put("pd", pd);
				result = (null == pd) ?  "02" :  "01";
					
			}else {
				result = "03";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
	
	/**
	 * 注册用户  需要一个ID  注册码的ID
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/register")
	@ResponseBody
	public Object register(HttpServletRequest request) throws UnsupportedEncodingException{
		logBefore(logger, "注册用户");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("registered", pd)){	//检查参数
				PageData p = new PageData();
				p = appuserService.getPhoneCode(pd);
				String code = (String) pd.get("CODE");
				if(p.get("CODE").equals(code)){//短信验证码是否正确
					 pd.put("USER_ID",this.get32UUID());
					 pd.put("ROLE_ID","d5fbc7cc85a6483dbe7728d2cd659e88");
					 pd.put("NUMBER",  NumberUtil.randomNumber());
					 pd.put("PHONE", pd.get("PHONE"));
					// pd.put("PASSWORD", pd.get("PASSWORD"));
					 pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
					 pd.put("IMG_URL_SMALL",new String("/uploadFiles/uploadImgs/1.jpg"));
					 pd.put("IMG_URL_BIG", new String("/uploadFiles/uploadImgs/2.jpg"));
					 pd.put("NAME", pd.get("USERNAME"));
					 pd.put("USERNAME", pd.get("USERNAME"));
					 appuserService.saveU(pd); 
					 //初始化用户菜单
					 List <PageData> menuList = intMenuService.getUserMenu(pd);
					 pd.put("STATUS", 1);
					 
					 for(int i=0;i<menuList.size();i++){
						 pd.put("AID",this.get32UUID());//中间表的主键
						 pd.put("MENU_ID", menuList.get(i).getString("MENU_ID"));
						 intMenuService.insertUserMenu(pd);
					 }
					 result = "01";
					 map.put("pd", pd);
				}else{
					result="06"; //短信验证码错误
				}
					
			}else {
				result = "03";
			}
			
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 是否存在一样的用户名
	 * @param username  用户名
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/isExistUsername")
	@ResponseBody
	public Object isExistUsername(HttpServletResponse response) throws Exception{
		logBefore(logger, "注册用户");
		PageData pd = new PageData();
		Map<String,Object> map = new HashMap<String,Object>();
		pd = this.getPageData();
		String result = "00";
		if(appuserService.isExistUsername(pd)>0){
			result= "07";
		}else{
			result="08";
		}
		map.put("result", result);
		return AppUtil.returnObject(new PageData(), map);
	}
	/**
	 * 获取备忘录标签
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getMemoryTag")
	@ResponseBody
	public Object getMemoryTag(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取备忘录标签");
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject memoryTag = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getGroup", pd)){
				List<PageData> memoryTagList = new ArrayList<PageData>();
				memoryTagList = appuserService.getMemoryTag(pd);
				JSONArray rows = JSONArray.fromObject(memoryTagList);
				result = (null == memoryTagList) ?  "02" :  "01";
				memoryTag.put("rows", rows);
			}else{
				result="03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			memoryTag.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, memoryTag);
		return null;
	}
	
	/**
	 * 获取备忘录  根据标签
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getMemory")
	@ResponseBody
	public Object getMemory(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取备忘录");
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject memory = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("getMemory", pd)){
				List<PageData> memoryList = new ArrayList<PageData>();
				pd.put("TIME", StringUtil.formatLike((String) pd.get("TIME")));
				memoryList = appuserService.getMemory(pd);
				JSONArray rows = JSONArray.fromObject(memoryList);
				result = (null == memoryList) ?  "02" :  "01";
				memory.put("rows", rows);
			}else{
				result="03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			memory.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, memory);
		return null;
	}
	
	/**
	 * 新增备忘录标签
	 * @param response    U_ID  用户ID  
	 * 					  NAME  名字
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping(value="/saveMemoryTag")
	@ResponseBody
	public Object saveMemoryTag(HttpServletResponse response) throws Exception{
		logBefore(logger, "新增备忘录标签");
		JSONObject workAdvice = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("saveMemoryTag", pd)){
				pd.put("ID", this.get32UUID());
				pd.put("STATUS", 1);
				appuserService.saveMemoryTag(pd);
				result =  "02";
			}else{ 
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workAdvice.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workAdvice);
		return null;
	}
	
	/**
	 * 新增备忘录
	 * @param response    U_ID  用户ID  
	 * 					  CONTENT  名字
	 * 					  CREATE_TIME 创建时间
	 * 					  TYPE_ID  标签ID	
	 * @return				
	 * @throws Exception
	 */
	
	@RequestMapping(value="/saveMemory")
	@ResponseBody
	public Object saveMemory(HttpServletResponse response) throws Exception{
		logBefore(logger, "新增备忘录标签");
		JSONObject workAdvice = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(AppUtil.checkParam("saveMemory", pd)){
				pd.put("ID", this.get32UUID());
				appuserService.saveMemory(pd);
				result =  "02";
			}else{ 
				result = "03";
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			workAdvice.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, workAdvice);
		return null;
	}
	/**
	 * 获取我的收藏
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getCollection")
	@ResponseBody
	public Object getCollection(HttpServletResponse response) throws Exception{
		logBefore(logger, "获取收藏");
		Map<String,Object> map = new HashMap<String,Object>();
		JSONObject collection = new JSONObject();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			List<PageData> collectionList = new ArrayList<PageData>();
			collectionList = appuserService.getCollection(pd);
			JSONArray rows = JSONArray.fromObject(collectionList);
			result = (null == collectionList) ?  "02" :  "01";
			collection.put("rows", rows);
		}catch(Exception e){
			logger.error(e.toString(), e);
		}finally{
			collection.put("result", result);
			logAfter(logger);
		}
		ResponseUtil.write(response, collection);
		return null;
	}
	
	
	/*
	 * 更新用户Logo
	 * param U_ID
	 */
	@RequestMapping(value="/updateUserlogo")
	@ResponseBody
	public Object updateCompany(
			@RequestParam(required=false) MultipartFile file
			) throws Exception{
		logBefore(logger, "更新公司Logo");
		Map<String,String> map = new HashMap<String,String>();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			String  ffile = DateUtil.getDays(), fileName = "";
			if (null != file && !file.isEmpty()) {
				String filePath = PathUtil.getClasspath() + Const.FILEPATHIMG + ffile;		//文件上传路径
				fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
			}else{
				System.out.println("上传失败");
			}
			pd.put("PATH", ffile + "/" + fileName);
			appuserService.updateUserlogo(pd);
			map.put("result", "ok");
		}catch (Exception e) {
			logger.error(e.toString(), e);
		}finally {
			logAfter(logger);
		}
		
		return AppUtil.returnObject(pd, map);
	}
}
	
 